package com.puzzlebazar.client.util;


import java.util.Vector;

/**
 * @author beaudoin
 *
 */
public abstract class ObservableImpl implements Observable {	
	
	private transient Vector<Observer> observers = new Vector<Observer>();
	private transient boolean changeFlag = false;
	
	@Override
	public void addObserver(Observer o) throws NullPointerException {
		if( o == null )
			throw new NullPointerException();		
		observers.add(o);
		o.update(this,null);
	}
	
	@Override
	public void deleteObserver(Observer o) {
		observers.remove(o);
	}	
	
	@Override
	public void deleteObservers() {
		observers.clear();
	}

	/**
	 * Indicates that this object has no longer changed, or that it has 
	 * already notified all of its observers of its most recent change, 
	 * so that the hasChanged method will now return false. This method 
	 * is called automatically by the notifyObservers methods. 
	 */
	protected void clearChanged() {
		changeFlag = false;
	}	

	/**
	 * Tests if this object has changed. 
	 * 
	 * @return true if and only if the setChanged method has been called 
	 * more recently than the clearChanged method on this object; 
	 * false otherwise.
	 */
	protected boolean hasChanged() {
		return changeFlag;
	}
	
	
	@Override
	public int countObservers() {
		return observers.size();
	}
	

	@Override
	public void notifyObservers() {
		notifyObservers(null);
	}
	
	@Override
	public void notifyObservers(Object arg) {
		if (!changeFlag) return;

		for (Observer observer : observers)
			observer.update(this, arg);			
		
		clearChanged();
	}
	

	@Override
	public void setChanged() {
		changeFlag = true;
	}	
	
	@Override
	public void release() {
		deleteObservers();
	}
}
